package pers.cz.redis;

import cn.hutool.core.date.DateUtil;
import pers.cz.commons.collection_server.InterfaceSyncToDb;
import pers.cz.model.AutoCollectTestCaseWithBLOBs;
import pers.cz.thread.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

/**
 * 接口队列消费类（同步redis中的接口消息到mysql数据库）
 * @program: PostGirl-panent
 * @description: InterfaceSyncCustomer
 * @author: Cheng Zhi
 * @create: 2022-02-08 12:33
 **/
public class InterfaceSyncThread implements Runnable{

    private Logger logger = LoggerFactory.getLogger(InterfaceSyncThread.class);

    private Jedis resource;

    private volatile Boolean flag = false;

    private final Integer timeOut = 0;          // 设置为0表示阻塞

    private final Long SLEEP_TIME = 60000L;     // 提交数据库间隔时间

    private final Integer BATCH_NUMBER = 200;   // 批量提交数

    private Thread t;
    // 初始化一个指定长度的list防止扩容带来的性能损耗
    private final List<AutoCollectTestCaseWithBLOBs> list=new ArrayList<AutoCollectTestCaseWithBLOBs>(1000);

    public synchronized void stopThread(){
        flag = true;
    }

    public InterfaceSyncThread(Jedis resource) {
        this.resource = resource;

        // 初始化一个线程用来提交数据库
        t = new Thread() {
            @Override
            public void run() {
                ThreadUtils.doSleep(240000);
                doTask();
            }

            private void doTask() {
                while(true) {
                    List<AutoCollectTestCaseWithBLOBs> todo = null;
                    synchronized (list) {
                        if(list.size()>0){
                            todo=new ArrayList<AutoCollectTestCaseWithBLOBs>(list);
                            list.clear();
                        }
                    }
                    if(todo!=null){
                        // 批量插入数据库
                        InterfaceSyncToDb.SyncToDb(todo);
                    }
                    ThreadUtils.doSleep(SLEEP_TIME);
                }
            }
        };
        t.start();
    }


    @Override
    public void run() {

        while(!flag) {
            delSync();
        }
    }

    /**
     * 同步进程
     */
    public void delSync() {

        // 消费
        List<String> interfaceListQueue = resource.brpop(timeOut,"COLLECTIONQUEUE");
        logger.debug(Thread.currentThread().getName() + "------接收到同步请求-------");
        if (interfaceListQueue != null && interfaceListQueue.size() > 0) {

            String interfaces = interfaceListQueue.get(1); // 取下标为1的， 下标为0表示的是key
            String[] interfacesArrays = interfaces.split("\\|\\|");
            if (interfaceListQueue.size() > 0) {
                String source = interfacesArrays[0];
                String busiCode = interfacesArrays[1];
                String request = interfacesArrays[2];
                String response = interfacesArrays[3];
                String traceId = interfacesArrays[5];  // interfacesArrays[4]表示的是busiCode

                AutoCollectTestCaseWithBLOBs autoCollectTestCaseWithBLOBs = new AutoCollectTestCaseWithBLOBs();
                autoCollectTestCaseWithBLOBs.setBusiCode(busiCode);
                autoCollectTestCaseWithBLOBs.setRequest(request);
                autoCollectTestCaseWithBLOBs.setResponse(response);
                autoCollectTestCaseWithBLOBs.setExt1(source);
                autoCollectTestCaseWithBLOBs.setExt2(traceId);
                autoCollectTestCaseWithBLOBs.setSyncTime(DateUtil.date());
                doInsert(autoCollectTestCaseWithBLOBs);
            }
        }
    }

    private void doInsert(AutoCollectTestCaseWithBLOBs autoCollectTestCaseWithBLOBs) {
        List<AutoCollectTestCaseWithBLOBs> todo = null;
        synchronized (list) {
            list.add(autoCollectTestCaseWithBLOBs);
            if(list.size()>=BATCH_NUMBER){
                todo=new ArrayList<AutoCollectTestCaseWithBLOBs>(list);
                list.clear();
            }
        }
        if(todo!=null){
            // 批量插入数据库
            InterfaceSyncToDb.SyncToDb(todo);
        }
    }
}
